<template>
  <div class="content">
    <el-form ref="ruleFormRef"   v-loading="loading" :model="ruleForm" status-icon :rules="rules" label-width="auto"
      class="demo-ruleForm">
      <el-form-item label="所属上级" prop="pid">
        <el-tree-select
          v-model="ruleForm.pid"
          :data="tableData"
          placeholder="请选择上级单位"
          default-expand-all
          :props="{ label: 'name', value: 'id' }"
          check-strictly
          clearable
          filterable
          :disabled="disabled"
          :render-after-expand="false"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="单位名称" prop="name">
        <el-input v-model="ruleForm.name" type="text" placeholder="请输入单位名称" autocomplete="off" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="单位地址" prop="address">
        <el-input v-model="ruleForm.address" type="text" placeholder="请输入单位地址" autocomplete="off" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="电话号码" prop="phone">
        <el-input v-model="ruleForm.phone" type="text" placeholder="请输入电话号码" autocomplete="off" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model.number="ruleForm.sort" type="number" placeholder="请输入排序" autocomplete="off" :disabled="disabled"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="ruleForm.status" size="small" :disabled="disabled">
          <el-radio :value="1" size="small">
            
          </el-radio>
          <el-radio :value="2" size="small">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="content">
        <el-input v-model="ruleForm.content" autosize :disabled="disabled"
        type="textarea" placeholder="请输入内容" autocomplete="off" />
      </el-form-item>
      <el-form-item v-if="props.type !== 'info'">
        <el-button size="large"  type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
        <el-button size="large" @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref,defineEmits,defineProps   } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useRoute } from "vue-router";
import { companyApi } from '@/utils/api/company';
import { ElMessage } from 'element-plus'
const props = defineProps({
  id: Number,
  type: String
});
const disabled = ref(false)
if(props.type ==='info'){
  disabled.value = true
}
// 定义自定义事件
const emits = defineEmits(['close-dialog']);
// 使用 useRoute 获取参数
const route = useRoute();
let {params} = route
const loading = ref(false)


const convertToTree = (data: any[]): Tree[] => {
  const tree = [];
    const map = {};

    // 第一步：创建一个以 id 为键的映射表
    data.forEach(item => {
        map[item.id] = { ...item, children: [] };
    });

    // 第二步：找出所有可能的父节点 id
    const allParentIds = new Set(data.map(item => item.pid));

    // 第三步：构建树形结构
    data.forEach(item => {
        if (!map[item.pid]) {
            // 如果该元素的 pid 不在 map 中，说明它没有父级，是根节点
            tree.push(map[item.id]);
        } else {
            // 否则，找到其父节点并将其添加到父节点的 children 数组中
            const parent = map[item.pid];
            if (parent) {
                parent.children.push(map[item.id]);
            }
        }
    });

    return tree;
}


const getCompanyInfo =  async(id:string) => {
  // 这里是获取单位信息的接口
  loading.value = true
   const res =  await companyApi.info({id:id})
  loading.value = false
 Object.assign(ruleForm,res.data)
}

const tableData = ref([
  {
    id: 0,
    name: '一级部门',
  }
])
const backData = ref({
  title:'添加单位'
})
const ruleFormRef = ref < FormInstance > ()

interface IForm {
  id : string
  pid: string
  name: string
  address: string
  phone: string
  sort: string
  status: string
  content: string
}

const ruleForm = reactive<IForm>({
  id:null,
  pid: 0,
  name: '',
  address: '',
  phone: '',
  sort: 10,
  status: '1',
  content: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  pid: [{ required: true, message: '请选择上级单位', trigger: 'blur' }],
  name: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入单位地址', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
})


const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      loading.value = true
      if(ruleForm.id == null){
        companyApi.create(ruleForm).then((res) => {
        loading.value = false
          if (res.code === 200) {
            emits('close-dialog');
          }else{
            ElMessage.error(res.msg)
          }
        })
      }else{
        companyApi.update(ruleForm).then((res) => {
          loading.value = false
          if (res.code === 200) {
            emits('close-dialog');
          }else{
            ElMessage.error(res.msg)
          }
        })
      }
     
    } else {
      loading.value = false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

onMounted(  () => {
  // 获取数据
  if(props.id){
    getCompanyInfo(props.id)
  }

  companyApi.getAll({}).then((res) => {
    if (res.code === 200) {
      tableData.value = tableData.value.concat(convertToTree(res.data))
    } 
  })
 
})
</script>

<style scoped>
.demo-ruleForm {
 background: #fff;
 padding: 20px;
 margin-top: 10px;
}
</style>
